import { defineStore } from 'pinia'
import { ipcService } from '@renderer/services/ipcService'

// 定义类型
export interface ConnectionEvent {
  clientId: string
  ip: string
  timestamp: string
  connected: boolean
}

export interface LogEvent {
  type: 'connection' | 'disconnection' | 'message' | 'info' | 'error'
  timestamp: string
  message: string
}

export const useWebSocketStore = defineStore('websocket', {
  state: () => ({
    activeConnections: [] as ConnectionEvent[],
    eventLogs: [] as LogEvent[],
    isServerActive: true,
    clientMessages: {} as Record<string, string>,
    connectionCleanup: undefined as (() => void) | undefined,
    disconnectionCleanup: undefined as (() => void) | undefined,
    messageCleanup: undefined as (() => void) | undefined
  }),

  getters: {
    activeConnectionCount(state) {
      return state.activeConnections.filter(c => c.connected).length
    },
    serverStatusText(state) {
      return state.isServerActive ? '运行中' : '已停止'
    }
  },

  actions: {
    // 初始化监听器
    initListeners() {
      this.cleanupListeners()

      // 添加连接监听器
      this.connectionCleanup = ipcService.onWebSocketConnection((event: ConnectionEvent) => {
        this.addConnection({ ...event, connected: true })
        this.addLog('connection', `客户端 ${event.clientId} (${event.ip}) 已连接`)
      })

      // 添加断开连接监听器
      this.disconnectionCleanup = ipcService.onWebSocketDisconnection((event: ConnectionEvent) => {
        this.removeConnection({ ...event, connected: false })
        this.addLog('disconnection', `客户端 ${event.clientId} (${event.ip}) 已断开`)
      })

      // 添加消息监听器
      this.messageCleanup = ipcService.onWebSocketMessage((event: any) => {
        console.log('收到客户端消息:', event);

        if (typeof event === 'object' && event !== null) {
          if ('clientId' in event && 'message' in event) {
            this.addLog('message', `来自 ${event.clientId}: ${event.message}`);
          } else if ('type' in event && event.type === 'NODE_LIST_RESPONSE') {
            this.addLog('info', `收到节点列表: ${event.data?.nodeCount || 0} 个节点`);
          } else {
            this.addLog('message', `来自客户端: ${JSON.stringify(event)}`);
          }
        } else {
          this.addLog('message', `来自客户端: ${event}`);
        }
      })
      this.syncClientList();
    },

    // 同步客户端列表
    async syncClientList() {
      try {
        this.addLog('info', '正在同步客户端列表...');
        // 调用IPC获取当前所有客户端
        const clients = await ipcService.getSocketClients();

        if (Array.isArray(clients)) {
          // 先清空现有连接
          this.activeConnections = [];

          // 添加所有客户端
          clients.forEach((client: ConnectionEvent) => {
            this.addConnection({
              ...client,
              connected: true
            });

            // 初始化消息字段
            if (this.clientMessages[client.clientId] === undefined) {
              this.clientMessages[client.clientId] = '';
            }
          });

          this.addLog('info', `已同步 ${clients.length} 个客户端连接状态`);
        }
      } catch (error) {
        this.addLog('error', `同步客户端列表失败: ${error instanceof Error ? error.message : String(error)}`);
      }
    },

    // 清理监听器
    cleanupListeners() {
      if (this.connectionCleanup) {
        this.connectionCleanup();
        this.connectionCleanup = undefined;
      }
      if (this.disconnectionCleanup) {
        this.disconnectionCleanup();
        this.disconnectionCleanup = undefined;
      }
      if (this.messageCleanup) {
        this.messageCleanup();
        this.messageCleanup = undefined;
      }
    },

    addConnection(event: ConnectionEvent) {
      const existingIndex = this.activeConnections.findIndex(c => c.clientId === event.clientId);

      if (existingIndex !== -1) {
        this.activeConnections[existingIndex] = {
          ...this.activeConnections[existingIndex],
          ...event
        };
      } else {
        this.activeConnections.push(event);
        this.clientMessages[event.clientId] = '';
      }
    },

    removeConnection(event: ConnectionEvent) {
      const index = this.activeConnections.findIndex(c => c.clientId === event.clientId);

      if (index !== -1) {
        this.activeConnections[index].connected = false;
      }
    },

    addLog(type: LogEvent['type'], message: string) {
      this.eventLogs.push({
        type,
        timestamp: new Date().toISOString(),
        message
      });
    },

    clearLogs() {
      this.eventLogs = [];
    },

    async broadcastMessage(message: string) {
      if (!message.trim()) return false;

      try {
        await ipcService.broadcastMessage(message);
        this.addLog('info', `广播消息: ${message}`);
        return true;
      } catch (error) {
        this.addLog('error', `广播失败: ${error instanceof Error ? error.message : String(error)}`);
        return false;
      }
    },

    async sendToClient(clientId: string, message: string) {
      if (!message.trim()) return false;

      try {
        const { success } = await ipcService.sendToClient(clientId, message, 'GET_NODE_LIST');
        if (success) {
          this.addLog('info', `发送给 ${clientId}: ${message}`);
          return true;
        } else {
          this.addLog('error', `发送给 ${clientId} 失败: 客户端可能已断开`);
          return false;
        }
      } catch (error) {
        this.addLog('error', `发送失败: ${error instanceof Error ? error.message : String(error)}`);
        return false;
      }
    }
  }
})
